package com.lq.file.filemanager.service.ftp;

import com.lq.file.filemanager.entity.FtpFileServer;
import com.lq.file.filemanager.server.client.MyFtpClient;
import com.lq.file.filemanager.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @program: file-manager
 * @description:
 * @author: LQ
 * @create: 2021-08-07 10:16
 */
@Service("FtpFileService")
@Slf4j
public class FtpFileServiceImpl implements FileService {

    @Autowired
    private MyFtpClient myFtpClient;
    @Autowired
    FtpFileServer ftpFileServer;
    @Autowired
    FTPClient ftpClient;

    @Override
    public String readFileToBase64(String remoteFileName, String remoteDir) throws Exception {
        byte[] bytes = readFileToByte(remoteFileName, remoteDir);
        String base64 = new String((new BASE64Encoder()).encodeBuffer(bytes));
        return base64;
    }


    public byte[] readFileToByte(String remoteFileName, String remoteDir) throws Exception {
        // FTPClient ftpClient = myFtpClient.ftpClient();
        if(!ftpClient.isConnected()){
            ftpClient = myFtpClient.ftpClient();
        }
        if (ftpClient == null) {
            return null;
        }

        InputStream inputStream = null;
        byte[] bytes = {};
        try {
            ftpClient.changeWorkingDirectory(remoteDir);
            FTPFile[] ftpFiles = ftpClient.listFiles(remoteDir);
            Boolean flag = false;
            //遍历当前目录下的文件，判断要读取的文件是否在当前目录下
            for (FTPFile ftpFile : ftpFiles) {
                if (ftpFile.getName().equals(remoteFileName)) {
                    flag = true;
                }
            }

            if (!flag) {
                log.error("directory：{}下没有 {}", remoteDir, remoteFileName);
                throw new Exception("directory：" + remoteDir + "下没有 " + remoteFileName);
            }
            //获取待读文件输入流
            inputStream = ftpClient.retrieveFileStream(remoteDir + remoteFileName);
            //inputStream.available() 获取返回在不阻塞的情况下能读取的字节数，正常情况是文件的大小
            bytes = new byte[inputStream.available()];
            //将文件数据读到字节数组中
            inputStream.read(bytes);
            log.info("read file {} success", remoteFileName);
            ftpClient.logout();
        } catch (IOException e) {
            log.error("read file fail ----->>>{}", e.getCause());
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("disconnect fail ------->>>{}", e.getCause());
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("inputStream close fail -------- {}", e.getCause());
                }
            }

        }

        return bytes;
    }

    @Override
    public String readFileToBase64(HttpServletRequest request, HttpServletResponse response, String remoteFileName, String remoteDir) {
        String msg = null;
        try {
            String fileType = ".pdf";
            response.setContentType("application/x-download");
            response.setContentType("application/" + fileType + ";charset=GB2312");
            response.setHeader("Content-disposition", "attachment; filename=" + remoteFileName);
            byte[] fileData = readFileToByte(remoteFileName, remoteDir);
            InputStream is = null;
            BufferedInputStream bis = null;
            ServletOutputStream out = null;
            try {
                is = new ByteArrayInputStream(fileData);
                bis = new BufferedInputStream(is);
                out = response.getOutputStream();
                byte[] buff = new byte[1024];

                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff))) {
                    out.write(buff, 0, bytesRead);
                    out.flush();
                }
            } finally {
                try {
                    is.close();
                    bis.close();
                    out.close();
                } catch (Exception var25) {
                }

            }
        } catch (Exception var28) {
            msg = "保存当前表单为WORD发生错误：" + var28.getMessage();
        }
        return msg;
    }

    @Override
    public void download(String remoteFileName, String localFileName, String remoteDir) {

    }

    @Override
    public boolean uploadFile(InputStream inputStream, String originName, String remoteDir) {
        return false;
    }
}
